package com.zy.baselib.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

open class MultiItemTypeAdapter<T>(val data: MutableList<T> = mutableListOf()): RecyclerView.Adapter<ViewHolder>() {

    private val mTypeViewDelegateManager = TypeViewDelegateManager<T>()

    override fun getItemViewType(position: Int): Int {
        if(!useItemViewDelegateManager) {
            return super.getItemViewType(position)
        }
        return mTypeViewDelegateManager.getItemViewType(data[position], position)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemDelegate = mTypeViewDelegateManager.getItemViewDelegate(viewType)
        val layoutId = itemDelegate.getItemViewLayoutId()
        val itemView = LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
        return ViewHolder(itemView)
    }

    override fun getItemCount() = data.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        mTypeViewDelegateManager.convert(holder, data[position], position)
    }

    private val useItemViewDelegateManager: Boolean get() = mTypeViewDelegateManager.count > 0

    protected fun addItemViewDelegate(typeViewDelegate: TypeViewDelegate<T>) {
        mTypeViewDelegateManager.addDelegate(typeViewDelegate)
    }

    protected fun addItemViewDelegate(viewType: Int, typeViewDelegate: TypeViewDelegate<T>) {
        mTypeViewDelegateManager.addDelegate(viewType, typeViewDelegate)
    }
}